<template>
  <div class="flexContent1">
    <div class="form_content">
      <el-form style="flex:1;" ref="genericForm" :disabled="routeType === 'detail'" :rules="genericFormRules"
        :model="genericForm" label-position="right" label-width="120px" class="demo-ruleForm">
        <div class="basic">非标商品信息</div>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-clearEmoji v-model.trim="genericForm.name" style="width: 80%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品助记符" prop="mnemonic">
              <el-input v-clearEmoji disabled v-model.trim="genericForm.mnemonic" style="width: 80%" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category">
              <!-- <el-input v-clearEmoji
                v-model.trim="genericForm.category"
                style="width: 80%"
                placeholder="请输入..."
              /> -->
              <el-select @click.native="getCategoryList" v-model="genericForm.category" filterable popper-class="eloption"
                style="width: 80%">
                <el-option v-for="(val, key) in categoryList" :key="key" :value="key" :label="val" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="销售单位" prop="unit">
              <el-radio-group v-model="genericForm.unit" size="small">
                <el-radio label="0">KG</el-radio>
                <!-- <el-radio label="1">数量</el-radio> -->
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="进货价(元/KG)" prop="purchasePrice">
              <el-input v-clearEmoji v-model.trim="genericForm.purchasePrice" :disabled="routeType !== 'add'"
                style="width: 80%" placeholder="元" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出仓价(元/KG)" prop="outboundPrice">
              <el-input v-clearEmoji v-model.trim="genericForm.outboundPrice" :disabled="routeType !== 'add'"
                style="width: 80%" placeholder="元" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="配送规格" prop="deliveryNorms">
              <el-input v-clearEmoji v-model.trim="genericForm.deliveryNorms" style="width: 80%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品状态" prop="status">
              <el-radio-group v-model="genericForm.status" size="small">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
                <el-radio label="2">淘汰</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="毛利率(%)" prop="grossRate">
              <el-input v-clearEmoji v-model.trim="genericForm.grossRate" disabled style="width: 80%" placeholder="">
                <svg-icon color="#ccc" slot="suffix" class="" icon-class="percent"
                  style="margin-top: 8px; font-size: 18px" />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="大包装" prop="bigPacking">
              <el-input v-clearEmoji v-model.trim="genericForm.bigPacking" style="width: 80%"
                :placeholder="routeType === 'detail' ? '' : '请输入'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="供应商" prop="firstSupplier">
              <el-select @click.native="getSCMList" v-model.trim="genericForm.firstSupplier"
                :placeholder="routeType === 'detail' ? '' : '请选择'" filterable clearable popper-class="eloption"
                style="width: 80%">
                <el-option v-for="firstSupplier in firstSupplierList" :key="firstSupplier.id" :value="firstSupplier.id"
                  :label="firstSupplier.supplierNum +
                    '   ' +
                    firstSupplier.name
                    " />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="箱规" prop="boxRule">
              <el-input v-clearEmoji v-model.trim="genericForm.boxRule" style="width: 80%"
                :placeholder="routeType === 'detail' ? '' : '请输入'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="保质期(天)" prop="expiryNum">
              <el-input v-clearEmoji v-model.trim="genericForm.expiryNum" style="width: 80%"
                :placeholder="routeType === 'detail' ? '' : '请输入'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产地" prop="producer">
              <el-input v-clearEmoji v-model.trim="genericForm.producer" style="width: 80%"
                :placeholder="routeType === 'detail' ? '' : '请输入'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="存储条件" prop="storage">
              <el-select @click.native="getStorageCondition" v-model.trim="genericForm.storage" popper-class="eloption"
                style="width: 80%" :placeholder="routeType === 'detail' ? '' : '请选择'">
                <el-option v-for="(val, key) in storageList" :key="key" :value="key" :label="val" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brandId">
              <el-select @click.native="getBrand" v-model.trim="genericForm.brandId" filterable clearable
                popper-class="eloption" style="width: 80%" :placeholder="routeType === 'detail' ? '' : '请选择'">
                <el-option v-for="brand in brandList" :key="brand.id" :value="brand.id" :label="brand.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-form-item label="商品一维码" prop="barCode">
              <el-input v-clearEmoji v-model.trim="genericForm.barCode" style="width: 80%"
                :placeholder="routeType === 'detail' ? '' : '请输入'" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片" prop="imgUrl">
              <el-upload v-if="!genericForm.imgUrl && routeType !== 'detail'" name="multipartFile" :limit="1"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" list-type="picture-card"
                :action="action" :data="upData" :headers="headers" :on-error="fileUploadError" class="imgUpload">
                <i size="12" class="el-icon-plus" />
                <br />
                <span class="txt">上传</span>
              </el-upload>
              <span v-if="!genericForm.imgUrl && routeType === 'detail'">无</span>
              <template v-if="genericForm.imgUrl">
                <div style="display: flex; width: 80%">
                  <!-- <img v-if="genericForm.imgUrl" :src="genericForm.imgUrl"
                    style="height: 50px;object-fit: cover;border: 1px solid #ccc;" alt="" /> -->
                  <el-image v-if="genericForm.imgUrl" style="height: 128px;object-fit: cover;border: 1px solid #ccc;"
                    :src="genericForm.imgUrl" :preview-src-list="[genericForm.imgUrl]">
                  </el-image>
                  <div v-if="routeType !== 'detail'" style="
											width: 50px;
                      height: 50px;
											border-radius: 5px;
											border: 1px dashed #ccc;
											text-align: center;
											color: #ccc;
											margin-left: 5px;
										">
                    <i style="cursor: pointer" class="el-icon-delete" @click="delImg" />
                  </div>
                </div>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="btnDiv">
        <el-button v-if="routeType === 'add' || routeType === ''" style="width: 88px;" class="submitBtn"
          @click.stop="addBtn">
          确定
        </el-button>
        <el-button v-if="routeType === 'edit'" class="submitBtn" style="width: 88px;" @click.stop="updateGoodsDetail">
          提交
        </el-button>
        <el-button v-if="routeType !== 'detail'" style="width: 88px;" class="celBtn" @click.stop="cancelbtn">
          取消
        </el-button>
        <el-button v-if="routeType === 'detail'" style="width: 88px;" class="celBtn" @click.stop="cancelbtn">
          返回
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { DecimalUtils } from '@/utils/math'
import { getToken } from '@/utils/auth';
import {
  genericGoodsAdd,
  genericGoodsEdit,
  getGenericGoodsDetail
} from '@/api/genericGoods';
import { getSCMList } from '@/api/scm';
import { getBrandEasy } from '@/api/goods';
import {
  getDictValueAndNameSource,
  getStorageCondition
} from '@/api/dictionary';
import { pinyin } from 'pinyin-pro';
export default {
  name: 'AddGenericGoods',
  data() {
    return {
      headers: { token: getToken() },
      action: process.env.VUE_APP_UPLOAD_BASE_API + '/file/uploadFile',
      upData: {
        fileType: '0'
      },
      routeType: 'add',
      id: '',
      genericForm: {
        name: '',
        mnemonic: '',
        imgUrl: '',
        bigPacking: '',
        boxRule: '',
        firstSupplier: '',
        category: '',
        storage: '',
        brandId: '',
        producer: '',
        grossRate: '', // 毛利率
        expiryNum: '', // 保质期
        deliveryNorms: '', // 配送规格
        purchasePrice: '', //进货价
        outboundPrice: '', // 出仓价
        unit: null, // 销售单位（0：kg,1：数量）
        status: '', // 状态：0.正常，1.停用，2.淘汰
        barCode: '' // 一维码
      },
      firstSupplierList: [],
      categoryList: [],
      brandList: [],
      storageList: {},
      genericFormRules: {
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 50,
            message: '商品名称不能超过50个字符',
            trigger: 'blur'
          }
        ],
        category: [
          {
            required: true,
            message: '请选择商品分类',
            trigger: 'change'
          }
        ],
        producer: [{
          min: 0,
          max: 30,
          message: '最多输入30个字符',
          trigger: 'blur'
        }],
        expiryNum: [
          {
            pattern: /^\+?[0-9]\d*$/,
            message: '请输入数字',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 20,
            message: '保质期应为0-20位数字',
            trigger: 'blur'
          },
        ],
        bigPacking: [
          {
            pattern: /^\+?[0-9]\d*$/,
            message: '请输入数字',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 20,
            message: '大包装应为0-20位数字',
            trigger: 'blur'
          },
        ],
        unit: [
          {
            required: true,
            message: '请选择商品单位',
            trigger: 'change'
          }
        ],
        deliveryNorms: [
          {
            required: true,
            message: '请输入配送规格',
            trigger: 'change'
          },
          {
            pattern: /^(?!(^0$|0\.0{1,2}$))[0-9]+(\.[0-9]{1,2})?$/,
            message: '只能输入数字或两位小数',
            trigger: 'blur'
          }
        ],
        barCode: [
          {
            min: 0,
            max: 20,
            message: '商品一维码应为1-20位数字',
            trigger: 'blur'
          },
          {
            pattern: /^\+?[0-9]\d*$/,
            message: '只能输入数字',
            trigger: 'blur'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择商品状态',
            trigger: 'blur'
          }
        ],
        purchasePrice: [
          {
            required: true,
            message: '请输入商品进货价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
            message: '进货价只能是数字或小数',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 10,
            message: '进货价应为1-10位数字',
            trigger: 'blur'
          }
        ],
        outboundPrice: [
          {
            required: true,
            message: '请输入商品出仓价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
            message: '出仓价只能是数字或小数',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 10,
            message: '出仓价应为1-10位数字',
            trigger: 'blur'
          }
        ],
        imgUrl: [
          {
            required: true,
            message: '请上传商品图片',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  watch: {
    genericForm: {
      handler(newVal, oldVal) {
        if (newVal.outboundPrice && newVal.purchasePrice) {
          const num = DecimalUtils.divide(DecimalUtils.subtract(newVal.outboundPrice, newVal.purchasePrice), newVal.outboundPrice)
          const grossRate = (num * 100).toFixed(2);
          if (isNaN(grossRate)) this.genericForm.grossRate = '0.00';
          else this.genericForm.grossRate = grossRate;
        } else {
          this.genericForm.grossRate = '';
        }
        if (newVal.name) {
          var reg = /[\u4e00-\u9fa5A-Za-z]/g;
          var names = newVal.name.match(reg);
          if (names) {
            name = names.join('');
            this.genericForm.mnemonic = pinyin(name, {
              pattern: 'first'
            })
              .toUpperCase()
              .replace(/\s*/g, '');
          } else {
            this.genericForm.mnemonic = '';
          }
        } else {
          this.genericForm.mnemonic = '';
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getBrand();
    this.getSCMList();
    this.getStorageCondition();
    this.init();
    this.getCategoryList();
    this.routeType = this.$route.query.routeType
      ? this.$route.query.routeType
      : 'add';
    this.id = this.$route.query?.id;
    if (this.id) {
      this.getGenericGoodsDetail();
    }
    console.log(this.id, 'id');
  },
  methods: {
    // 获取数据字典的数据
    async getStorageCondition() {
      const res = await getStorageCondition();
      if (res.code === 200) {
        this.storageList = res.data;
        // this.genericForm.storage = res.data[0].key
        // this.$set(this.genericForm, 'storage', res.data[0]);
        // console.log('存储条件', this.genericForm.storage);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getBrand() {
      const res = await getBrandEasy();
      if (res.code === 200) {
        // const data = res.data
        const data = res.data;
        this.brandList = data.brandList;
        // console.log(data)
        // console.log('品牌', this.brandList)
      } else {
        // this.$message.error(res.message);
      }
    },
    async getSCMList() {
      const res = await getSCMList();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data.list;
      }
    },
    init() {
      this.genericForm = {
        name: '',
        mnemonic: '',
        imgUrl: '',
        storage: '0',
        category: '7',
        purchasePrice: '', //进货价
        outboundPrice: '', // 出仓价
        unit: '0', // 销售单位（0：kg,1：数量）
        status: '0', // 状态：0.正常，1.停用，2.淘汰
        brandId: '0417580e779b4d689518af3452712b47',
        barCode: '' // 一维码
      };
    },
    async getCategoryList() {
      const res = await getDictValueAndNameSource('NONSTANDARD_CATEGORY');
      this.categoryList = res.data;
      console.log(this.categoryList, 'this.categoryList');
    },
    async getGenericGoodsDetail() {
      const res = await getGenericGoodsDetail({ id: this.id });
      if (res.code === 200) {
        console.log(res.data, 'res.data');
        this.genericForm = res.data;
        this.$set(
          this.genericForm,
          'purchasePrice',
          String(res.data.purchasePrice ? res.data.purchasePrice : 0)
        );
        this.$set(
          this.genericForm,
          'outboundPrice',
          String(res.data.outboundPrice ? res.data.outboundPrice : 0)
        );
        this.$set(
          this.genericForm,
          'deliveryNorms',
          String(res.data.deliveryNorms ? res.data.deliveryNorms : 0)
        );
        this.$set(
          this.genericForm,
          'expiryNum',
          String(res.data.expiryNum ? res.data.expiryNum : 0)
        );
        this.$set(
          this.genericForm,
          'bigPacking',
          String(res.data.bigPacking ? res.data.bigPacking : 0)
        );
        this.$set(
          this.genericForm,
          'grossRate',
          String(res.data.grossRate ? res.data.grossRate : 0)
        );
      } else {
        // this.$message.error("获取数据失败");
      }
    },
    addBtn() {
      this.$refs.genericForm.validate(async isOk => {
        if (isOk) {
          const res = await genericGoodsAdd(this.genericForm);
          console.log(res.code);
          if (res.code === 200) {
            this.$message.success('添加成功');
            this.$refs.genericForm.resetFields();
            this.closeTag('genericGoodsInfo');
          } else {
            // this.$message.error(res.message);
          }
        } else {
          this.$message.warning('请检查填写的信息');
        }
      });
    },
    cancelbtn() {
      // this.$refs.genericForm.resetFields()
      this.closeTag('genericGoodsInfo');
    },
    handleAvatarSuccess(res, file) {
      this.genericForm.imgUrl =
        this.$store.getters.imgBaseUrl +
        res.data.filePath +
        res.data.fileNewName;
      console.log(this.$store.getters.imgBaseUrl, '基地址');
      console.log(res);
      this.$message.success('上传成功');
      console.log(this.genericForm.imgUrl);
    },
    beforeAvatarUpload(file) {
      // console.log('before', file)
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf('.'));
      const isOKType =
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg';
      if (!isOKType) {
        this.$message.error('图片格式只能为jpeg/png/jpg');
      }

      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!');
      }
      return isLt2M && isOKType;
    },
    delImg() {
      this.genericForm.imgUrl = '';
    },
    fileUploadError(res) {
      this.$message.error(res.message);
    },
    async updateGoodsDetail() {
      this.$refs.genericForm.validate(async isOk => {
        if (isOk) {
          const res = await genericGoodsEdit(this.genericForm);
          console.log(res.code);
          if (res.code === 200) {
            this.$message.success('修改成功');
            this.$refs.genericForm.resetFields();
            this.$router.push('genericGoodsInfo');
          } else {
            // this.$message.error(res.message);
          }
        } else {
          this.$message.warning('请检查填写的信息');
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.btnDiv {
  display: flex;
  // text-align: right;
  // padding-left: 90%;
  justify-content: end;

}

.flexContent1 {
  // padding: 32px;
  height: 100%;

  /* background-color: #fff; */
  .form_content {
    padding: 32px;
    height: 100%;
    // padding-top: 50px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .imgUpload {
      ::v-deep .el-upload:hover {
        border-color: #409eff;
      }

      ::v-deep .el-upload {
        position: relative;
        margin-bottom: 10px;
        margin-left: 5px;
        width: 70px;
        height: 70px;
        line-height: 30px;
        padding-top: 5px;
      }

      .txt {
        color: #595858;
        font-size: 12px;
      }
    }
  }
}

.basic {
  font-family: PingFang SC, PingFang SC;
  font-size: 20px;
  color: rgba(0, 0, 0, 0.9);
  margin-bottom: 32px;
}

.el-upload--picture-card i {
  font-size: 12px !important;
}

.el-button--small {
  padding: 9px 0;
}

::deep el-button {
  text-align: center;
}

// .el-row {
//   margin-bottom: 20px;

//   &:last-child {
//     margin-bottom: 0;
//   }
// }

.el-form-item--small.el-form-item {
  margin-bottom: 26px !important;
}

::v-deep .el-icon-circle-close:before {
  color: #fff;
}
</style>
